<script lang="ts" setup>
import {computed, onMounted, ref, watch} from 'vue'
import {getGoodsCategoriesAPI,getGoodsByShopIdAPI,getGoodsDetailAPI,updateGoodsAPI,downloadImagesAPI,deleteGoodsAPI} from '@/apis/goods'
import {RegionFullText, RegionSelects} from "v-region";
import {useUserStore} from '@/stores/user'
import router from '@/router/index'
import TagGroup from "@/views/shop/componets/tagGroup.vue";
import ImgUploader from "@/views/shop/componets/imgUploader.vue";
import {ElMessage, ElMessageBox, FormInstance, UploadUserFile} from "element-plus";

onMounted(()=>{
  getGoodsCategories()
  getAllGoods()
})

const select=ref('byTitle')
const searchName=ref('')
const options = ref([])
const category=ref([])
const goodsList=ref([])

const imgFile=ref([])

const categoryMap=new Map()
const getGoodsCategories= async ()=>{
  const res=await getGoodsCategoriesAPI()
  if(res.code===200){
    options.value=res.data
    //存入map
    res.data.forEach(parent=>{
      categoryMap.set(parent.value,parent.label)
      parent.children.forEach(son=>{
        categoryMap.set(son.value,son.label)
        son.children.forEach(grandson=>{
          categoryMap.set(grandson.value,grandson.label)
        })
      })
    })
  }
}
const props = {
  expandTrigger: 'hover' as const,
}

async function getAllGoods() {
  const res=await getGoodsByShopIdAPI(useUserStore().myShop.shopId)
  if(res.code===200){
    goodsList.value=res.data
    goodsList.value.forEach((item) => {
      if (typeof item.tags === "string") {
        item.tags = item.tags.split(',')
      }
    })
  }
}

const goodsListFilter=computed(()=>{
  return goodsList.value.filter(item=>{
    const matchesId=select.value==='byId'?item.gid.toString().includes(searchName.value):true
    const matchesTitle=select.value==='byTitle'?item.title.includes(searchName.value):true
    const matchesCategory=category.value.length&&item.category!==null?item.category.includes(category.value[category.value.length-1]):true
    return matchesId && matchesTitle && matchesCategory
  })
})

function clearSearch() {
  searchName.value=''
  category.value=[]
}
const editDialogVisible=ref(false)
const imgUploader=ref()
const formRef = ref<FormInstance>()
const form = ref({
  shopId:useUserStore().myShop.shopId,
  gid:'',
  title: '',
  category:[],
  price:'',
  imgs:[],
  desc:'',
  tags:[],
  origin:{
    province:'',
    city:''
  },
  stock:'',
  isOnline:1
})

const rules={
  title:[
    { type: 'string',required: true,message: "必填", trigger: 'blur'},
    {max: 30,message: "标题长度不能超过30位" }
  ],
  category:[
    { type: 'array',required: true,message: "请选择商品种类", trigger: 'blur'},
  ],
  price:[
    { required: true,message: "必填", trigger: 'blur'},
    {type:'number',message: "价格不正确"}
  ],
  desc:[],
  tags:[],
  origin:[
    {type: 'object', required: true,message: "请选择产地", trigger: 'blur'},
  ],
  stock:[
    { type: 'number',required: true,message: "必填", trigger: 'blur'},
  ],
}

async function editGoods(goods) {
  //防止重复发送请求
  if(form.value.gid===goods.gid){
    editDialogVisible.value=true
    return
  }
  const res=await getGoodsDetailAPI(goods.gid)
  form.value.category=[]
  form.value.gid=goods.gid
  form.value.title=goods.title
  form.value.category.push(parseInt(goods.category.slice(0,3)))
  form.value.category.push(parseInt(goods.category.slice(0,5)))
  form.value.category.push(parseInt(goods.category))
  form.value.price=goods.g_price
  //获取商品旧图
  imgFile.value=[]
  if(res.goodsImg!==null){
    res.goodsImg.forEach(imgUrl=>{
      downloadImage(imgUrl)
    })
  }
  form.value.desc=goods.description
  form.value.tags=goods.tags
  form.value.origin.province=goods.province
  form.value.origin.city=goods.city
  form.value.stock=parseInt(goods.stock_quantity)
  form.value.isOnline=goods.isOnline
  editDialogVisible.value=true
}

function downloadImage(imgUrl):object{
  fetch(imgUrl,{
    mode:'cors'
  }).then(res=>res.blob()).then(blob=>{
    // 将文件数据流保存到本地
    console.log("blob",blob)

    const file = new File([blob], blob.size+'.'+blob.type.slice(6), {type: blob.type,encoding: 'utf-8'})

    file.uid=new Date().getTime()
    const objectURL = window.URL.createObjectURL(blob)
    const ITEM={
      uid:file.uid,
      name:file.name,
      percentage:0,
      raw:file,
      size:file.size,
      status:'success',//因为是已经通过url缓存下来的图片，所以设为success
      url:objectURL
    }
    imgFile.value.push(ITEM)
  }).catch(err => {
    console.error('文件下载失败')
    return null
  });
}

async function updateGoods() {
  const formData = new FormData();
  imgFile.value.forEach((file,index) => {

    console.log(`开始上传第${index+1}张图片`,file.raw)
    formData.append('files', file.raw);

  })
  const newGoods={
    gid:form.value.gid,
    title:form.value.title,
    stock_quantity:form.value.stock,
    g_price:form.value.price,
    tags:form.value.tags.toString(),
    province:form.value.origin.province,
    city:form.value.origin.city,
    category:form.value.category[2],
    description:form.value.desc,
    isDelete:0
  }
  //转成Blob类型，不然会乱码
  const goodsJsonBlob = new Blob([JSON.stringify(newGoods)], { type: 'application/json' });
  formData.append('goods',goodsJsonBlob)
  const res= await updateGoodsAPI(formData)
  ElMessage({
    type:res.code===200?'success':'error',
    message:res.code===200?'保存成功':'修改失败'
  })
  if(res.code===200){
    //刷新本地数据
    await getAllGoods()
    form.value.gid=-1
    editDialogVisible.value=false
  }
}


const handleUpdate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if(imgFile.value.length===0){
        ElMessage({
          type:'error',
          message:"至少上传一张图片"
        })
        return
      }
      if(form.value.origin.city===undefined){
        ElMessage({
          type:'error',
          message:"请选择产地"
        })
        return
      }
      //装载图片
      imgUploader.value.submitUpload()
      updateGoods()
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 删除商品函数
async function deleteGoods(goods) {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品"${goods.title}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const res = await deleteGoodsAPI(goods.gid)
    
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '商品删除成功'
      })
      // 刷新商品列表
      await getAllGoods()
    } else {
      ElMessage({
        type: 'error',
        message: res.message || '删除失败'
      })
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage({
        type: 'error',
        message: '删除操作失败'
      })
    }
  }
}

</script>

<template>
  <div class="panel">
    <h1>我的商品</h1>
    <el-input
        v-model="searchName"
        style="width: 300px"
        placeholder="请输入内容"
        class="input-with-select"
    >
      <template #prepend>
        <el-select v-model="select" placeholder="请选择" style="width: 115px">
          <el-option label="商品标题" value="byTitle"  />
          <el-option label="商品ID" value="byId" />
        </el-select>
      </template>
    </el-input>
    <span>&nbsp;分类</span>
    <el-cascader
        v-model="category"
        :options="options"
        :props="props"
    />
    &nbsp;
    <el-button type="danger" @click="clearSearch">重置</el-button>

    <div class="table-container">
    <el-table :data="goodsListFilter" style="width: 100%;margin-top: 50px">
      <el-table-column prop="gid" label="编号" width="100" />
      <el-table-column prop="title" label="商品名" width="180" />
      <el-table-column prop="" label="图片" width="100" >
        <template #default="scope">
          <img style="width: 50px;height: 50px" :src="scope.row.img" alt="">
        </template>
      </el-table-column>
      <el-table-column prop="g_price" label="价格" width="100" />
      <el-table-column prop="stock_quantity" label="库存" width="100" />
      <el-table-column prop="turnover" label="销量" width="100" />
      <el-table-column prop="" label="种类" width="120" >
        <template #default="scope">
          {{categoryMap.get(parseInt(scope.row.category) )}}
        </template>
      </el-table-column>
      <el-table-column prop="" label="标签" width="180" >
        <template #default="scope">
          <el-tag v-for="tag in scope.row.tags" type="primary" style="margin-right: 5px">{{tag}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" width="180" />

        <el-table-column prop="" label="原产地" width="100" >
          <template #default="scope">
            <RegionFullText separator="-" v-model="scope.row"/>
          </template>
        </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <div class="optionGroup">
          <span v-if="scope.row.isOnline" style="color: #f56c6c">下架</span>
            <span v-if="!scope.row.isOnline" style="color:#1df114">上架</span>
            &nbsp;
          <span @click="editGoods(scope.row)">编辑</span>&nbsp;
          <span @click="deleteGoods(scope.row)" style="color: #f56c6c; cursor: pointer;">删除</span>&nbsp;
            <span @click="router.push(`/detail/${scope.row.gid}`)">查看</span>
          </div>
        </template>
        </el-table-column>
    </el-table>
    </div>
    <el-dialog v-model="editDialogVisible" title="编辑" width="800">

      <el-form :model="form" :rules="rules" ref="formRef" label-width="auto" style="max-width: 600px">
        <el-form-item label="商品标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-cascader
              v-model="form.category"
              :options="options"
              :props="props"
              :show-all-levels="false"
          />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model.number="form.price"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" >
          <img-uploader v-model:file="imgFile" ref="imgUploader"></img-uploader>
        </el-form-item>
        <el-form-item label="商品描述" prop="desc">
          <el-input v-model="form.desc" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <tag-group v-model="form.tags"/>
        </el-form-item>
        <el-form-item label="原产地" >
          <RegionSelects :area="false"  v-model="form.origin"/>
        </el-form-item>
        <el-form-item label="库存量" prop="stock">
          <el-input v-model.number="form.stock"></el-input>
        </el-form-item>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate(formRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<style scoped lang="less">
.panel {
  width: 100%;
  max-width: 990px;
  min-height: 700px;
  background-color: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
}

.optionGroup {
  span {
    cursor: pointer;
    transition: color 0.3s;
    
    &:hover {
      color: #007bff;
    }
    
    &[style*="color: #f56c6c"] {
      &:hover {
        color: #dc3545;
      }
    }
    
    &[style*="color:#1df114"] {
      &:hover {
        color: #28a745;
      }
    }
  }
}

.table-container {
  margin-top: 20px;
  height: 600px;
  overflow: auto;
  
  :deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    
    .el-table__header {
      background-color: #f8f9fa;
    }
    
    .el-table__row {
      &:hover {
        background-color: #f0f7ff;
      }
    }
  }
}

.hover-col:hover {
  cursor: pointer;
  color: #007bff;
}

:deep(.el-dialog) {
  border-radius: 8px;
  
  .el-dialog__header {
    background-color: #f8f9fa;
    padding: 20px 30px;
    border-bottom: 1px solid #e9ecef;
  }
  
  .el-dialog__body {
    padding: 30px;
  }
  
  .el-dialog__footer {
    padding: 20px 30px;
    background-color: #f8f9fa;
    border-top: 1px solid #e9ecef;
  }
}

:deep(.el-form) {
  .el-form-item {
    margin-bottom: 24px;
    
    .el-input, .el-select, .el-cascader, .el-textarea {
      width: 100%;
    }
    
    .el-textarea {
      .el-textarea__inner {
        min-height: 100px;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
  
  .el-button {
    margin-left: 10px;
  }
}
</style>